package dxn.nl.export.deal.export;

import com.alibaba.fastjson2.JSON;
import dxn.nl.export.deal.netty.SocketManager;
import dxn.nl.file.biz.ExportStatusEnum;
import dxn.nl.file.biz.po.FileExportApplyDetail;
import dxn.nl.file.biz.service.ExportFileBaseService;
import dxn.nl.file.client.model.dto.CsExportExcelSheetHeadDto;
import dxn.nl.file.client.model.dto.TransferMessageDto;
import dxn.nl.file.client.model.enums.ExportFileTypeEnum;
import dxn.nl.file.client.model.enums.ExportMessageTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class ExportDealPageQueryBiz extends ExportDealBaseBiz
{
    private String currentParams;
    private static final Logger log = LoggerFactory.getLogger(ExportDealBaseBiz.class);

    public ExportDealPageQueryBiz(HashMap<String, CsExportExcelSheetHeadDto> sheetHeadMap, ExportFileBaseService exportFileBaseService, FileExportApplyDetail fileExportApplyDetail)
    {
        super(sheetHeadMap,exportFileBaseService, fileExportApplyDetail);
    }

    private void requestAndDealData()
    {
        TransferMessageDto sendMessage = new TransferMessageDto(ExportMessageTypeEnum.query_data.code,
                ExportFileTypeEnum.export.code, fileExportApplyDetail.getAppId(), fileExportApplyDetail.getModeCode(),
                fileExportApplyDetail.getOrgCode(), fileExportApplyDetail.getOrgName(), fileExportApplyDetail.getApplyUserCode(),
                fileExportApplyDetail.getApplyUserName());
        sendMessage.getConfig().setServer(SocketManager.appSessionId);
        byte[] bytes = null;
        if(fileExportApplyDetail.getParam() != null)
        {
            bytes = JSON.toJSONBytes(fileExportApplyDetail.getParam());
        }

        Set<String> sheetNames = getAllSheetName();

        for(String entry:sheetNames)
        {
            boolean continueDeal = true;
            while(continueDeal)
            {
                sendMessage.setType(ExportMessageTypeEnum.query_data.code);
                sendMessage.getMessageData().setSheetName(entry);
                sendMessage.getMessageData().setCurrentParam(currentParams);
                sendMessage.setData(bytes);

                sendMessage = SocketManager.sendData(sendMessage,false);
                currentParams = sendMessage.getMessageData().getCurrentParam();

                continueDeal = writerData(sendMessage);
            }
        }
    }

    public void dealExport()
    {
        try {
            // 修改导出状态为“表格制作中”
            exportFileBaseService.updateStatus(fileExportApplyDetail.getId(), ExportStatusEnum.start_deal,0,null);
            // 处理导出
            requestAndDealData();
        }
        catch (Exception ex)
        {
            log.error("",ex);
            failMessages.append(ex.getMessage());
        }
        // 结束，提交
        updateFinishStatus();
    }
}
